package com.mitgroup.dmrvs.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class CarDiagnoseActivity extends AppCompatActivity {
    private static final int MSG_LOAD = 1;
    private static final String BUNDLE_LOAD_FAIL ="load_fail";
    private static final String BUNDLE_LOAD_SUCCESS = "load_success";
    private static final String BUNDLE_INIT_LOAD_SUCCESS = "init_load_success";
    private static final String BUNDLE_LOCAL_ERROR = "local_error";
    private static final int MSG_DIAGNOSE = 2;
    private static final String BUNDLE_MSG_DIAGNOSE_FAIL = "diagnose_fail";
    private static final String BUNDLE_MSG_DIAGNOSE_SUCCESS = "read_success";
    private static final String BUNDLE_MSG_DIAGNOSE_JUMP = "diagnose_jump";
    private static final int MSG_CAR_DEL = 3;
    private static final String BUNDLE_MSG_CAR_DEL_FAIL ="car_del_fail";
    private static final String BUNDLE_MSG_CAR_DEL_SUCCESS = "car_del_success";
    private static final String BUNDLE_MSG_CAR_DEL_JUMP = "car_del_jump";
    public List<PullCarInfoBean> data = new ArrayList<PullCarInfoBean>();
    List<PullCarInfoBean> list = new ArrayList<PullCarInfoBean>();
    MyAdapter adapter;
    public String userId;
    public String province;
    private Intent intent;
    /**handler对象*/
    private Handler handler;
    private ProgressDialog progressDialog;
    @BindView(R.id.btn_back)
    public Button back;
    @OnClick(R.id.btn_back)
    public void onBack(View view) {
        this.finish();
    }
    @BindView(R.id.tv_user_name)
    public TextView tvUserName;
    @BindView(R.id.iv_quit)
    public Button quit;
    @OnClick(R.id.iv_quit)
    public void onQuit(View view) {
        Utils.Exit(this);
    }

    @BindView(R.id.btn_nav01)
    public Button btnReceiveCar;
    @OnClick(R.id.btn_nav01)
    public void onReceiveCar(View view) {
        intent = new Intent(CarDiagnoseActivity.this,
                ReceiveCarActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav02)
    public Button btnDiagnose;
    @BindView(R.id.btn_nav03)
    public Button btnSettings;
    @OnClick(R.id.btn_nav03)
    public void onSettings(View view) {
        intent = new Intent(CarDiagnoseActivity.this,
                SettingsActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_car_diagnose)
    public Button btnCarDiagnose;

    @BindView(R.id.btn_intake)
    public Button btnIntake;
    @BindView( R.id.btn_fuel)
    public Button btnFuel;
    @BindView(R.id.btn_twc)
    public Button btnTwc;
    @BindView( R.id.btn_ac)
    public Button btnAc;
    @OnClick({R.id.btn_intake,R.id.btn_fuel,R.id.btn_twc,R.id.btn_ac})
    public void onDetector(View view) {
        switch (view.getId()) {
            case R.id.btn_twc:
                intent = new Intent(CarDiagnoseActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "twc");
                startActivity(intent);
                this.finish();

                break;
            case R.id.btn_intake:
                intent = new Intent(CarDiagnoseActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "intake");
                startActivity(intent);
                this.finish();

                break;
            case R.id.btn_ac:
                intent = new Intent(CarDiagnoseActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "ac");
                startActivity(intent);
                this.finish();
                break;
            case R.id.btn_fuel:
                intent = new Intent(CarDiagnoseActivity.this,
                        DetectorActivity.class);
                intent.putExtra("detector", "fuel");
                startActivity(intent);
                this.finish();
                break;
        }
    }
    @BindView(R.id.lv_car_info)
    public PullToRefreshListView pullToRefresh;
    @BindView(R.id.et_query_condition)
    public EditText etQueryCondition;
    @BindView(R.id.btn_query_car_info)
    public Button btnQuery;
    @OnClick(R.id.btn_query_car_info)
    public void onQueryCarInfo(View view) {
         condition=etQueryCondition.getText().toString();
         firstRow=1;
         lastRow=5;

        List<PullCarInfoBean>   data1=new ArrayList<PullCarInfoBean>();
        adapter = new MyAdapter(CarDiagnoseActivity.this,data1);
        pullToRefresh.setAdapter(adapter);
        pullToRefresh.setMode(PullToRefreshBase.Mode.BOTH);
        getCarInfo(userId,condition,firstRow,lastRow);
    }
    public int page=0;
    public int firstRow=1;
    public int lastRow=5;
    public int totalRow=0;
    public int totalPage=0;
    public int step=5;
    public String condition="";
    List<PullCarInfoBean> list1 = new ArrayList<PullCarInfoBean>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_diagnose);
        ButterKnife.bind(this);
        initView();
    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
         userId = PreferencesUtils.getString(CarDiagnoseActivity.this, "userId");
         String userName = PreferencesUtils.getString(CarDiagnoseActivity.this, "userName");
        tvUserName.setText(userName);
        province=PreferencesUtils.getString(CarDiagnoseActivity.this,"province");
        btnDiagnose.setBackgroundResource(R.drawable.nav_icon02_active);
        btnCarDiagnose.setVisibility(View.GONE);
        initListView();

        getCarInfo(userId,condition,firstRow,lastRow);
        pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>(){
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                new FinishRefresh().execute();
                if(totalPage!=0) {
                    adapter.notifyDataSetChanged();
                }
            }
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if(totalPage!=0) {
                page+=1;
                firstRow=lastRow+1;
                if(page!=totalPage && page<totalPage)
                {
                    lastRow+=step;
                }
                else
                {
                    if(page>totalPage)
                    {
                        Toast.makeText(CarDiagnoseActivity.this,"已到最后！", Toast.LENGTH_SHORT).show();
                        Bundle bundle = new Bundle();
                        Message msg;
                        bundle.putString(BUNDLE_LOAD_SUCCESS, "加载成功！");
                        msg = myHandler.obtainMessage();
                        msg.what = MSG_LOAD;
                        msg.setData(bundle);
                        myHandler.sendMessage(msg);
                        return;
                    }
                    else
                    {
                        lastRow=firstRow+totalRow%step;
                    }
                }
                if(page!=0) {
                    final String[] key = {"userId", "condition", "firstRow", "lastRow"};
                    final String[] value = {userId, condition, firstRow + "", lastRow + ""};
                    progressDialog = ProgressDialog.show(CarDiagnoseActivity.this,
                            getResources().getString(R.string.notice), "正在加载中...");
                    new Thread(new Runnable() {
                        Bundle bundle = new Bundle();
                        Message msg;

                        @Override
                        public void run() {
                            String rs = "";
                            try {

                                rs = WSClient.soapGetInfo("getCarInfoByUserId", key, value);
                                if (rs != null && !"".equals(rs)) {
                                    JSONTokener jsonTokener = new JSONTokener(rs);
                                    JSONObject jsonObject = (JSONObject) jsonTokener
                                            .nextValue();
                                    String status = jsonObject.getString("status");

                                    String content = jsonObject.get("content").toString();

                                    if ("1".equals(status)) {
                                        JSONArray jsonArray = new JSONArray(content);

                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject infoJson = jsonArray.getJSONObject(i);
                                            PullCarInfoBean bean = new PullCarInfoBean();
                                            bean.setCar_info_id(infoJson.getInt("carInfoId"));
                                            bean.setPlate_number(infoJson.getString("plateNumber"));
                                            bean.setCar_vin(infoJson.getString("carVin"));
                                            bean.setCar_brand(infoJson.getString("carBrand"));
                                            bean.setFamily_name(infoJson.getString("familyName"));
                                            bean.setEngine_desc(infoJson.getString("engineDesc"));
                                            bean.setGearbox_name(infoJson.getString("gearboxName"));
                                            bean.setYear_pattern(infoJson.getString("yearPattern"));
                                            bean.setFuel_jet_type(infoJson.getString("fuelJetType"));
                                            bean.setSupply_oil(infoJson.getString("supplyOil"));
                                            bean.setVehicle_name(infoJson.getString("vehicleName"));
                                            bean.setReceive_car_date(infoJson.getString("receiveCarDate"));
                                            bean.setMileage(infoJson.getInt("mileage"));
                                            bean.setBuy_car_date(infoJson.getString("buyCarDate"));
                                            bean.setResult(infoJson.getString("mresult"));
                                            bean.setProduct(infoJson.getString("mproduct"));
                                            bean.setIntakeImg(infoJson.getString("intakeImg"));
                                            bean.setAcImg(infoJson.getString("acImg"));
                                            bean.setFuelImg(infoJson.getString("fuelImg"));
                                            bean.setTwcImg(infoJson.getString("twcImg"));
                                            bean.setIntakeLevel(infoJson.getString("intakeLevel"));
                                            bean.setAcLevel(infoJson.getString("acLevel"));
                                            bean.setFuelLevel(infoJson.getString("fuelLevel"));
                                            bean.setTwcLevel(infoJson.getString("twcLevel"));
                                            list1.add(bean);
                                        }

                                        bundle.putString(BUNDLE_LOAD_SUCCESS, "加载成功！");
                                    } else {
                                        bundle.putString(BUNDLE_LOAD_FAIL, "无数据加载！");
                                    }
                                } else {
                                    bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                                }
                            } catch (Exception e) {
                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                            }
                            msg = myHandler.obtainMessage();
                            msg.what = MSG_LOAD;
                            msg.setData(bundle);
                            myHandler.sendMessage(msg);

                        }
                    }).start();
                  }

                }
                else
                {
                    Toast.makeText(CarDiagnoseActivity.this,"加载成功！", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void initListView()
    {
        ILoadingLayout startLabels = pullToRefresh
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

        ILoadingLayout endLabels = pullToRefresh.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("正在载入...");// 刷新时
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

        // 设置下拉刷新文本
        pullToRefresh.getLoadingLayoutProxy(false, true)
                .setPullLabel("上拉刷新...");
        pullToRefresh.getLoadingLayoutProxy(false, true).setReleaseLabel(
                "放开刷新...");
        pullToRefresh.getLoadingLayoutProxy(false, true).setRefreshingLabel(
                "正在加载...");
        // 设置上拉刷新文本
//        			pullToRefresh.getLoadingLayoutProxy(true, false)
//        					.setPullLabel("下拉刷新...");
//        			pullToRefresh.getLoadingLayoutProxy(true, false).setReleaseLabel(
//        					"放开刷新...");
//        			pullToRefresh.getLoadingLayoutProxy(true, false).setRefreshingLabel(
//        					"正在加载...");
    }
    private void getCarInfo(String userId,String condition,int firstRow,int lastRow){
        final String []key={"userId","condition","firstRow","lastRow"};
        final String []value={userId,condition,firstRow+"",lastRow+""};
        progressDialog = ProgressDialog.show(CarDiagnoseActivity.this,
                getResources().getString(R.string.notice), "正在加载中...");
        new Thread(new Runnable() {
            Bundle bundle = new Bundle();
            Message msg;
            @Override
            public void run() {
                String rs = "";
                try {
                    rs = WSClient.soapGetInfo("getCarInfoByUserId",key,value);
                    if(rs!=null &&!"".equals(rs))
                    {
                        JSONTokener jsonTokener = new JSONTokener(rs);
                        JSONObject jsonObject = (JSONObject) jsonTokener
                                .nextValue();
                        String status = jsonObject.getString("status");
                        totalRow = Integer.parseInt(jsonObject.getString("total"));
                        totalPage=totalRow/step;
                        if(totalRow%step!=0)
                        {
                            totalPage+=1;
                        }
                        String content = jsonObject.get("content").toString();

                        if("1".equals(status))
                        {
                            JSONArray jsonArray = new JSONArray(content);
                            page=1;
                            list.clear();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject infoJson = jsonArray.getJSONObject(i);
                                PullCarInfoBean bean = new PullCarInfoBean();

                                bean.setCar_info_id(infoJson.getInt("carInfoId"));
                                bean.setPlate_number(infoJson.getString("plateNumber"));
                                bean.setCar_vin(infoJson.getString("carVin"));
                                bean.setCar_brand(infoJson.getString("carBrand"));
                                bean.setFamily_name(infoJson.getString("familyName"));
                                bean.setEngine_desc(infoJson.getString("engineDesc"));
                                bean.setGearbox_name(infoJson.getString("gearboxName"));
                                bean.setYear_pattern(infoJson.getString("yearPattern"));
                                bean.setFuel_jet_type(infoJson.getString("fuelJetType"));
                                bean.setSupply_oil(infoJson.getString("supplyOil"));
                                bean.setVehicle_name(infoJson.getString("vehicleName"));
                                bean.setReceive_car_date(infoJson.getString("receiveCarDate"));
                                bean.setMileage(infoJson.getInt("mileage"));
                                bean.setBuy_car_date(infoJson.getString("buyCarDate"));
                                bean.setResult(infoJson.getString("mresult"));
                                bean.setProduct(infoJson.getString("mproduct"));
                                bean.setIntakeImg(infoJson.getString("intakeImg"));
                                bean.setAcImg(infoJson.getString("acImg"));
                                bean.setFuelImg(infoJson.getString("fuelImg"));
                                bean.setTwcImg(infoJson.getString("twcImg"));
                                bean.setIntakeLevel(infoJson.getString("intakeLevel"));
                                bean.setAcLevel(infoJson.getString("acLevel"));
                                bean.setFuelLevel(infoJson.getString("fuelLevel"));
                                bean.setTwcLevel(infoJson.getString("twcLevel"));
                                list.add(bean);
                            }

                            bundle.putString(BUNDLE_INIT_LOAD_SUCCESS, "加载成功！");
                        }
                        else
                        {
                            bundle.putString(BUNDLE_LOAD_FAIL, "无数据加载！");
                        }
                    }
                    else
                    {
                        bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                    }
                }
                catch (Exception e) {
                    bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                }
                msg = myHandler.obtainMessage();
                msg.what = MSG_LOAD;
                msg.setData(bundle);
                myHandler.sendMessage(msg);

            }
        }).start();

    }
    private Handler myHandler = new Handler() {
        String key="";
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case MSG_LOAD:
                    String key1 = msg.getData().keySet().iterator().next();
                    if (BUNDLE_LOAD_FAIL.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(CarDiagnoseActivity.this,msg.getData().getString(BUNDLE_LOAD_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(CarDiagnoseActivity.this,"服务器连接失败！", Toast.LENGTH_SHORT).show();

                    }
                    else if (BUNDLE_INIT_LOAD_SUCCESS.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        data=list;
                        adapter = new MyAdapter(CarDiagnoseActivity.this,data);
                        pullToRefresh.setAdapter(adapter);
                        pullToRefresh.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    else if (BUNDLE_LOAD_SUCCESS.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }

                        if(page>1)
                        {
                            if(list1!=null)
                            {
                                if(list1.size()!=0)
                                {
                                    for(int i=0;i<list1.size();i++)
                                    {
                                        adapter.addLast((PullCarInfoBean)list1.get(i));
                                        new FinishRefresh().execute();
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                                else
                                {
                                    new FinishRefresh().execute();
                                    adapter.notifyDataSetChanged();
                                }

                            }
                            else
                            {
                                new FinishRefresh().execute();
                                adapter.notifyDataSetChanged();
                            }
                            list1.clear();
                        }
                    }
                    break;
                case MSG_CAR_DEL:
                    key = msg.getData().keySet().iterator().next();
                    if (BUNDLE_MSG_CAR_DEL_FAIL.equals(key)) {
                        Toast.makeText(CarDiagnoseActivity.this,msg.getData().getString(BUNDLE_MSG_CAR_DEL_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        Toast.makeText(CarDiagnoseActivity.this,"服务器连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_MSG_CAR_DEL_SUCCESS.equals(key)) {
                        Toast.makeText(CarDiagnoseActivity.this,msg.getData().getString(BUNDLE_MSG_CAR_DEL_SUCCESS), Toast.LENGTH_SHORT).show();
                        CarDiagnoseActivity.this.finish();
                        Intent intent = new Intent(CarDiagnoseActivity.this,
                                CarDiagnoseActivity.class);
                        startActivity(intent);
                    }
                    break;
                case MSG_DIAGNOSE:
                    key= msg.getData().keySet().iterator().next();
                    if (BUNDLE_MSG_DIAGNOSE_FAIL.equals(key)) {
                        Toast.makeText(CarDiagnoseActivity.this,msg.getData().getString(BUNDLE_MSG_DIAGNOSE_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {

                        Toast.makeText(CarDiagnoseActivity.this,"服务器连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_MSG_DIAGNOSE_SUCCESS.equals(key)) {
                        Toast.makeText(CarDiagnoseActivity.this,msg.getData().getString(BUNDLE_MSG_DIAGNOSE_SUCCESS), Toast.LENGTH_SHORT).show();
                        CarDiagnoseActivity.this.finish();
                        Intent intent = new Intent(CarDiagnoseActivity.this,
                                CarDiagnoseActivity.class);
                        startActivity(intent);
                    }
                    break;
                default:
                    break;
            }
            removeMessages(msg.what);
        }
    };
    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }
    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result){
//        	      	adapter.notifyDataSetChanged();
            pullToRefresh.onRefreshComplete();
        }
    }
    private class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        ViewHolder viewHolder = null;
        public MyAdapter(Context context, List<PullCarInfoBean> list) {
            Utils.initImageLoader(context);
            mInflater = LayoutInflater.from(context);
            data=list;
        }
        public void addFirst(PullCarInfoBean bean){
            data.add(0, bean);
        }
        public void addLast(PullCarInfoBean bean){
            data.add(bean);
        }
        @Override
        public int getCount() {
            return data.size();
        }
        @Override
        public Object getItem(int position) {
            return data.get(position);
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        public void removeItem(int position) {
            data.remove(position);
            this.notifyDataSetChanged();
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //String url="";
            if(convertView == null){
                viewHolder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.content_list_item_car_info, null);
                viewHolder.carInfoId = (TextView) convertView.findViewById(R.id.tv_car_info_id);
                viewHolder.receiveTime = (TextView) convertView.findViewById(R.id.tv_receive_time1);
                viewHolder.plateNumber = (TextView) convertView.findViewById(R.id.tv_plate_number1);
                viewHolder.carVin = (TextView) convertView.findViewById(R.id.tv_car_vin1);
                viewHolder.carBrand = (TextView) convertView.findViewById(R.id.tv_car_brand1);
                viewHolder.familyName = (TextView) convertView.findViewById(R.id.tv_family_name1);
                viewHolder.engineDesc = (TextView) convertView.findViewById(R.id.tv_engine_desc1);
                viewHolder.gearboxName = (TextView) convertView.findViewById(R.id.tv_gearbox_name1);
                viewHolder.yearPattern = (TextView) convertView.findViewById(R.id.tv_year_pattern1);
                viewHolder.fuelJetType = (TextView) convertView.findViewById(R.id.tv_fuel_jet_type1);
                viewHolder.supplyOil = (TextView) convertView.findViewById(R.id.tv_supply_oil1);
                viewHolder.vehicleName = (TextView) convertView.findViewById(R.id.tv_vehicle_name1);
                viewHolder.diagnoseResult=(TextView) convertView.findViewById(R.id.tv_diagnose_result1);
                viewHolder.product=(TextView) convertView.findViewById(R.id.tv_product);
                viewHolder.mileage = (TextView) convertView.findViewById(R.id.tv_mileage1);
                viewHolder.buyCarTime=(TextView) convertView.findViewById(R.id.tv_buy_car_time1);
                viewHolder.dispDiagnoseResult=(Button) convertView.findViewById(R.id.btn_dispdiagnose);

                viewHolder.diagnose=(Button) convertView.findViewById(R.id.btn_diagnose);
                viewHolder.carDel=(Button) convertView.findViewById(R.id.btn_car_del);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();        				}

            String carInfoId=data.get(position).getCar_info_id()+"";
            viewHolder.carInfoId.setText(carInfoId+"");
            String receiveTime=data.get(position).getReceive_car_date();
            viewHolder.receiveTime.setText(receiveTime);
            String plateNumber=data.get(position).getPlate_number();
            viewHolder.plateNumber.setText(plateNumber);
            String carVin=data.get(position).getCar_vin();
            viewHolder.carVin.setText(carVin);
            String carBrand=data.get(position).getCar_brand();
            viewHolder.carBrand.setText(carBrand);
            String familyName=data.get(position).getFamily_name();
            viewHolder.familyName.setText(familyName);
            String engineDesc=data.get(position).getEngine_desc();
            viewHolder.engineDesc.setText(engineDesc);
            String gearboxName=data.get(position).getGearbox_name();
            viewHolder.gearboxName.setText(gearboxName);
            String yearPattern=data.get(position).getYear_pattern();
            viewHolder.yearPattern.setText(yearPattern);
            String fuelJetType=data.get(position).getFuel_jet_type();
            viewHolder.fuelJetType.setText(fuelJetType);
            String supplyOil=data.get(position).getSupply_oil();
            viewHolder.supplyOil.setText(supplyOil);
            String vehicleName=data.get(position).getVehicle_name();
            viewHolder.vehicleName.setText(vehicleName);
            int mileage=data.get(position).getMileage();
            viewHolder.mileage.setText(mileage+"");
            String buyCarTime=data.get(position).getBuy_car_date();
            viewHolder.buyCarTime.setText(buyCarTime);
            String diagnoseResult=data.get(position).getResult();
            if(diagnoseResult!=null && !"".equals(diagnoseResult) && !"null".equals(diagnoseResult))
            {
                viewHolder.diagnoseResult.setText(diagnoseResult);
            }
            String product=data.get(position).getProduct();
            if(product!=null && !"".equals(product) && !"null".equals(product))
            {
                viewHolder.product.setText(product);
            }
            String intakeImg=data.get(position).getIntakeImg();
            if(intakeImg!=null && !"".equals(intakeImg) && !"null".equals(intakeImg))
            {
                viewHolder.product.setText(intakeImg);
            }
            String acImg=data.get(position).getAcImg();
            if(acImg!=null && !"".equals(acImg) && !"null".equals(acImg))
            {
                viewHolder.product.setText(acImg);
            }
            String fuelImg=data.get(position).getFuelImg();
            if(fuelImg!=null && !"".equals(fuelImg) && !"null".equals(fuelImg))
            {
                viewHolder.product.setText(fuelImg);
            }
            String twcImg=data.get(position).getTwcImg();
            if(twcImg!=null && !"".equals(twcImg) && !"null".equals(twcImg))
            {
                viewHolder.product.setText(twcImg);
            }
            String intakeLevel=data.get(position).getIntakeLevel();
            if(intakeLevel!=null && !"".equals(intakeLevel) && !"null".equals(intakeLevel))
            {
                viewHolder.product.setText(intakeLevel);
            }
            String acLevel=data.get(position).getAcLevel();
            if(acLevel!=null && !"".equals(acLevel) && !"null".equals(acLevel))
            {
                viewHolder.product.setText(acLevel);
            }
            String fuelLevel=data.get(position).getFuelLevel();
            if(fuelLevel!=null && !"".equals(fuelLevel) && !"null".equals(fuelLevel))
            {
                viewHolder.product.setText(fuelLevel);
            }
            String twcLevel=data.get(position).getTwcLevel();
            if(twcLevel!=null && !"".equals(twcLevel) && !"null".equals(twcLevel))
            {
                viewHolder.product.setText(twcLevel);
            }
            if(convertView!=null)
            {
                viewHolder.carDel.setOnClickListener(new lvButtonListener(position,carInfoId));
                if(diagnoseResult!=null && !"".equals(diagnoseResult)&& !"null".equals(diagnoseResult))
                {
                    viewHolder.dispDiagnoseResult.setOnClickListener(new lvButtonListener(position,carInfoId,plateNumber,receiveTime,province,mileage,buyCarTime,carVin,carBrand,familyName,engineDesc,gearboxName,yearPattern,fuelJetType,supplyOil,vehicleName,diagnoseResult,product,intakeImg,acImg,fuelImg,twcImg,intakeLevel,acLevel,fuelLevel,twcLevel));
                    viewHolder.dispDiagnoseResult.setVisibility(View.VISIBLE);
                    viewHolder.carDel.setEnabled(false);
                    //viewHolder.diagnose.setEnabled(false);
                }
                else
                {
                    viewHolder.dispDiagnoseResult.setVisibility(View.GONE);
                }

                viewHolder.diagnose.setOnClickListener(new lvButtonListener(position, carInfoId, plateNumber, receiveTime, province, mileage, buyCarTime,carVin,carBrand,familyName,engineDesc,gearboxName,yearPattern,fuelJetType,supplyOil,vehicleName,diagnoseResult,product,intakeImg,acImg,fuelImg,twcImg,intakeLevel,acLevel,fuelLevel,twcLevel));
            }
            return convertView;
        }

        class ViewHolder{
            TextView carInfoId;
            TextView plateNumber;
            TextView carVin;
            TextView carBrand;
            TextView familyName;
            TextView engineDesc;
            TextView gearboxName;
            TextView yearPattern;
            TextView fuelJetType;
            TextView supplyOil;
            TextView vehicleName;
            TextView receiveTime;
            TextView mileage;
            TextView buyCarTime;
            TextView diagnoseResult;
            TextView product;
            TextView intakeImg;
            TextView acImg;
            TextView fuelImg;
            TextView twcImg;
            TextView intakeLevel;
            TextView acLevel;
            TextView fuelLevel;
            TextView twcLevel;
            Button  carDel;
            Button diagnose;
            Button dispDiagnoseResult;

        }
        class lvButtonListener implements View.OnClickListener {
            private int position;
            private String myCarInfoId;
            private String myPlateNumber;
            private String myRecieveTime;
            private String myProvince;
            private int myMileage;
            private String myBuyCarTime;
            private String lastReceiveCarDate;
            private String myCarVin;
            private String myCarBrand;
            private String myFamilyName;
            private String myEngineDesc;
            private String myGearboxName;
            private String myYearPattern;
            private String myFuelJetType;
            private String mySupplyOil;
            private String myVehicleName;
            private String myDiagnoseResult;
            private String myProduct;
            private String myIntakeImg;
            private String myAcImg;
            private String myFuelImg;
            private String myTwcImg;
            private String myIntakeLevel;
            private String myAcLevel;
            private String myFuelLevel;
            private String myTwcLevel;
            lvButtonListener(int pos,String carInfoId) {
                position = pos;
                myCarInfoId=carInfoId;
            }
            lvButtonListener(int pos,String carInfoId,String plateNumber,String receiveTime,String province, int mileage, String buyCarTime,String carVin,String carBrand,String familyName,String engineDesc,String gearboxName,String yearPattern,String fuelJetType,String supplyOil,String veheicleName,String diagnoseResult,String product,String intakeImg,String acImg,String fuelImg,String twcImg, String intakeLevel,String acLevel,String fuelLevel,String twcLevel)
            {
                position = pos;
                myCarInfoId=carInfoId;
                myPlateNumber=plateNumber;
                myRecieveTime=receiveTime;
                myProvince=province;
                myMileage=mileage;
                myBuyCarTime=buyCarTime;
                myCarVin=carVin;
                myCarBrand=carBrand;
                myFamilyName=familyName;
                myEngineDesc=engineDesc;
                myGearboxName=gearboxName;
                myYearPattern=yearPattern;
                myFuelJetType=fuelJetType;
                mySupplyOil=supplyOil;
                myVehicleName=veheicleName;
                myDiagnoseResult=diagnoseResult;
                myProduct=product;
                myIntakeImg=intakeImg;
                myAcImg=acImg;
                myFuelImg=fuelImg;
                myTwcImg=twcImg;
                myIntakeLevel=intakeLevel;
                myAcLevel=acLevel;
                myFuelLevel=fuelLevel;
                myTwcLevel=twcLevel;
            }
            @Override
            public void onClick(View v) {

                int vid=v.getId();
                if (vid == viewHolder.dispDiagnoseResult.getId())
                {
                    Intent intent = new Intent(CarDiagnoseActivity.this,
                            DispDianoseResultActivity.class);
                    intent.putExtra("carInfoId", myCarInfoId);
                    intent.putExtra("plateNumber", myPlateNumber);
                    intent.putExtra("receiveTime", myRecieveTime);
                    intent.putExtra("buyCarTime", myBuyCarTime);
                    intent.putExtra("mileage", myMileage+"");
                    intent.putExtra("carVin", myCarVin);
                    intent.putExtra("carBrand", myCarBrand);
                    intent.putExtra("engineDesc", myEngineDesc);
                    intent.putExtra("familyName", myFamilyName);
                    intent.putExtra("gearboxName", myGearboxName);
                    intent.putExtra("yearPattern", myYearPattern);
                    intent.putExtra("fuelJetType", myFuelJetType);
                    intent.putExtra("supplyOil", mySupplyOil);
                    intent.putExtra("vehicleName", myVehicleName);
                    intent.putExtra("diagnoseResult", myDiagnoseResult);
                    intent.putExtra("product", myProduct);
//                    intent.putExtra("intakeImg", myIntakeImg);
//                    intent.putExtra("acImg", myAcImg);
//                    intent.putExtra("fuelImg", myFuelImg);
//                    intent.putExtra("twcImg", myTwcImg);
                    intent.putExtra("intakeLevel", myIntakeLevel);
                    intent.putExtra("acLevel", myAcLevel);
                    intent.putExtra("fuelLevel", myFuelLevel);
                    intent.putExtra("twcLevel", myTwcLevel);
                    startActivity(intent);
                }
                else  if (vid == viewHolder.diagnose.getId())
                {
                    if( myIntakeLevel==null||"".equals(myIntakeLevel) )
                    {
                        PreferencesUtils.putString(CarDiagnoseActivity.this,"carInfoId", myCarInfoId);
                        Toast.makeText(CarDiagnoseActivity.this,"请检测进气系统！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Date buyCarDate=null;
                    Date receiveDate=null;

                    Calendar ca = Calendar.getInstance();
                    try {
                        receiveDate = new SimpleDateFormat("yyyy-MM-dd").parse(myRecieveTime );
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    ca.setTime(receiveDate);
                    String receiveMonth=ca.get(Calendar.MONTH)+1+"";
                    try {
                        buyCarDate = new SimpleDateFormat("yyyy-MM-dd").parse(myBuyCarTime );
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    ca.setTime(buyCarDate);
                    int buyCarYear = ca.get(Calendar.YEAR);
                    Calendar cal = Calendar.getInstance();
                    int thisYear = cal.get(Calendar.YEAR);
                    int   aveMileage=0;
                    if(thisYear-buyCarYear>0)
                    {
                        aveMileage=myMileage/(thisYear-buyCarYear);
                    }
                    else {
                        aveMileage=myMileage;
                    }

                    int i=0;
                    String diagnoseResult="";
                    String product="";
                    if(aveMileage>10000)
                    {
                        final String []key={"carInfoId","plateNumber"};
                        final String []value={myCarInfoId+"",myPlateNumber};
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    String rs = WSClient.soapGetInfo("getLastReceiveCarDate",key,value);
                                    JSONTokener jsonTokener = new JSONTokener(rs);
                                    JSONObject jsonObject = (JSONObject) jsonTokener
                                            .nextValue();
                                    String status = jsonObject.getString("status");
                                    String content = jsonObject.get("content").toString();
                                    if("1".equals(status))
                                    {
                                        JSONObject jsonObject1 = jsonObject
                                                .getJSONObject("content");
                                        lastReceiveCarDate = jsonObject1.getString("lastReceiveCarDate");
                                    }
                                }
                                catch (Exception e) {
                                }

                            }
                        }).start();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }

                    }
                    if(myMileage>=5000)
                    {
                        i=myMileage/5000;
                        if(i==1)
                        {
                            diagnoseResult+="A:发动机主油道有油泥|";
                        }
                        else if(i>=2 && i<=4)
                        {
                            diagnoseResult+="A:发动机主油道，油底壳有油泥|";
                        }
                        else if(i>=5 && i<=6)
                        {
                            diagnoseResult+="A:发动机主油道、油底壳有油泥，活塞裙部有轻微清漆|";
                        }
                        else if(i>=7)
                        {
                            diagnoseResult+="A:发动机凸轮轴、主油道、油底壳有油泥，活塞裙部有清漆和积碳|";
                        }
                        product+="wa11000,";
                    }
                    if(myMileage>=10000)
                    {
                        i=myMileage/10000;
                        if(i==1)
                        {
                            diagnoseResult+="B:排放系统和三元催化转换器内表面有轻微碳层|";
                        }
                        else if(i>=2 && i<=3)
                        {
                            diagnoseResult+="B:排放系统和三元催化转换器内表面有积碳积聚|";
                        }
                        else if(i>=4 && i<=6)
                        {
                            diagnoseResult+="B:排放系统和三元催化转换器内表面有明显积碳，影响转换效率|";
                        }
                        else if(i>=7)
                        {
                            diagnoseResult+="B:排放系统和三元催化转换器内表面有明显积碳，影响转换效率，请关注尾气|";
                        }
                        product+="wa66101,";
                    }
                    if(myMileage>=20000)
                    {
                        i=myMileage/20000;
                        if(i==1)
                        {
                            diagnoseResult+="C:节气门体碟片背面有明显积碳，进气门和燃烧室表层有轻微积碳|";
                        }
                        else if(i==2)
                        {
                            diagnoseResult+="C:节气门体碟片背面有明显积碳，进气门和燃烧室表层有较明显积碳|";
                        }
                        else if(i==3)
                        {
                            diagnoseResult+="C:节气门体碟片背面有明显积碳，进气门和燃烧室表层有明显积碳|";
                        }
                        else if(i>=4)
                        {
                            diagnoseResult+="C:节气门体碟片背面有明显积碳，进气门和燃烧室表层有较严重积碳|";
                        }
                        product+="wa68102,wa60802,wa61510,";
                    }
                    if(myMileage>=40000)
                    {
                        i=myMileage/40000;
                        if(i==1)
                        {
                            diagnoseResult+="D:自动变速箱内部有轻微油泥，冷却系统内部有轻微水垢|";
                        }
                        else if(i==2)
                        {
                            diagnoseResult+="D:自动变速箱内部有较明显油泥，冷却系统内部有较明显水垢|";
                        }
                        else if(i>=3)
                        {
                            diagnoseResult+="D:自动变速箱内部有明显油泥，冷却系统内部有明显水垢|";
                        }
                        product+="wa64401,wa64506,waa4701,waa4601,wa62409,wa64805,";
                    }
                    String[]arrMonth1 = {"3","4","5","6","7","8","9"};
                    String[]arrMonth2 = {"4","5","6","7","8","9"};
                    String[]arrMonth3 = {"4","5","6","7","8"};
                    String[]arrMonth4 = {"5","6","7","8"};
                    String[]arrMonth5 = {"6","7","8"};
                    String[]arrProvince1 = {"海南"};
                    String[]arrProvince2 = {"广东","广西","重庆"};
                    String[]arrProvince3 = {"贵州","四川","福建","江西","湖南","湖北","浙江"};
                    String[]arrProvince4 = {"上海","山东","安徽","云南","江苏","山西","河北","河南","陕西","北京","天津"};
                    String[]arrProvince5 = {"辽宁","吉林","黑龙江","内蒙","甘肃","宁夏","青海","新疆"};
                    if( Arrays.asList(arrProvince1).contains(myProvince))
                    {
                        if(Arrays.asList(arrMonth1).contains(receiveMonth))
                        {
                            diagnoseResult+="E:建议检查并清洗蒸发箱和空调系统|";
                            product+="wa66701,wa30208,wa62801";
                        }
                    }
                    else if( Arrays.asList(arrProvince2).contains(myProvince))
                    {
                        if(Arrays.asList(arrMonth2).contains(receiveMonth))
                        {
                            diagnoseResult+="E:建议检查并清洗蒸发箱和空调系统|";
                            product+="wa66701,wa30208,wa62801";
                        }
                    }

                    else  if( Arrays.asList(arrProvince3).contains(myProvince))
                    {
                        if(Arrays.asList(arrMonth3).contains(receiveMonth))
                        {
                            diagnoseResult+="E:建议检查并清洗蒸发箱和空调系统|";
                            product+="wa66701,wa30208,wa62801";
                        }
                    }
                    else  if( Arrays.asList(arrProvince4).contains(myProvince))
                    {
                        if(Arrays.asList(arrMonth4).contains(receiveMonth))
                        {
                            diagnoseResult+="E:建议检查并清洗蒸发箱和空调系统|";
                            product+="wa66701,wa30208,wa62801";
                        }
                    }
                    else  if( Arrays.asList(arrProvince5).contains(myProvince))
                    {
                        if(Arrays.asList(arrMonth5).contains(receiveMonth))
                        {
                            diagnoseResult+="E:建议检查并清洗蒸发箱和空调系统|";
                            product+="wa66701,wa30208,wa62801";
                        }
                    }

                    if(lastReceiveCarDate!=null &&!"".equals(lastReceiveCarDate))
                    {
                        Calendar cal1=Calendar.getInstance();
                        try {
                            cal1.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(lastReceiveCarDate ));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        Calendar cal2=Calendar.getInstance();
                        cal2.setTime(new Date());
                        @SuppressLint("WrongConstant")
                        int subMonth=(cal2.get(1)-cal1.get(1))*12+(cal2.get(2)-cal1.get(2));
                        if(subMonth>=6)
                        {
                            diagnoseResult+="F:检查并清洗润滑系统";
                            //product+="wa11000,";
                        }
                    }
                    final String []key1={"carInfoId","mResult","mProduct"};
                    final String []value1={myCarInfoId+"",diagnoseResult,product};

                    new Thread(new Runnable() {
                        Bundle bundle = new Bundle();
                        Message msg;
                        @Override
                        public void run() {
                            try {
                                String rs = WSClient.soapGetInfo("updateCarInfoResult",key1,value1);

                                JSONTokener jsonTokener = new JSONTokener(rs);
                                JSONObject jsonObject = (JSONObject) jsonTokener
                                        .nextValue();
                                String status = jsonObject.getString("status");
                                String content = jsonObject.get("content").toString();

                                if("1".equals(status))
                                {

                                    bundle.putString(BUNDLE_MSG_DIAGNOSE_SUCCESS, "诊断成功！");


                                }
                                else
                                {
                                    bundle.putString(BUNDLE_MSG_DIAGNOSE_FAIL, content);
                                }
                            }
                            catch (Exception e) {
                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                            }
                            msg = myHandler.obtainMessage();
                            msg.what = MSG_DIAGNOSE;
                            msg.setData(bundle);
                            myHandler.sendMessage(msg);
                        }
                    }).start();
                }
                else if (vid == viewHolder.carDel.getId())
                {
                    new AlertDialog.Builder(CarDiagnoseActivity.this).setTitle("确认删除吗？")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final String []key1={"carInfoId"};
                                    final String []value1={myCarInfoId+""};

                                    new Thread(new Runnable() {
                                        Bundle bundle = new Bundle();
                                        Message msg;
                                        @Override
                                        public void run() {
                                            try {
                                                String rs = WSClient.soapGetInfo("updateCarInfoDelFlag",key1,value1);

                                                JSONTokener jsonTokener = new JSONTokener(rs);
                                                JSONObject jsonObject = (JSONObject) jsonTokener
                                                        .nextValue();
                                                String status = jsonObject.getString("status");
                                                String content = jsonObject.get("content").toString();

                                                if("1".equals(status))
                                                {

                                                    bundle.putString(BUNDLE_MSG_CAR_DEL_SUCCESS, "删除成功！");
//        		        									viewHolder.sceneCmdRead.setVisibility(View.GONE);
                                                    //removeItem(position);
                                                }
                                                else
                                                {
                                                    bundle.putString(BUNDLE_MSG_CAR_DEL_FAIL, content);
                                                }
                                            }
                                            catch (Exception e) {
                                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                                            }
                                            msg = myHandler.obtainMessage();
                                            msg.what = MSG_CAR_DEL;
                                            msg.setData(bundle);
                                            myHandler.sendMessage(msg);
                                        }
                                    }).start();
                                }
                            })
                            .setNegativeButton("返回", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“返回”后的操作,这里不设置没有任何操作
                                }
                            }).show();
//        		            	ViewInject.toast(myCmdId);

                }

            }
        }
    }
    protected void onDestroy() {
        super.onDestroy();
    }
}
